/**
 * @desc 封装了一些项目常用方法.
 */

// 内部函数, 用于判断对象类型
function _getClass(object: any): any {
  // @ts-ignore
  return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1]
}

export function isArray(obj: any) {
  return _getClass(obj).toLowerCase() === 'array'
}

export function isString(obj: any) {
  return _getClass(obj).toLowerCase() === 'string'
}

export function isDate(obj: any) {
  return _getClass(obj).toLowerCase() === 'date'
}

export function isObject(obj: any) {
  return _getClass(obj).toLowerCase() === 'object'
}

export function isNumber(obj: any) {
  return _getClass(obj).toLowerCase() === 'number'
}

export function isFormData(obj: any) {
  try {
    if (obj instanceof FormData) {
      return true
    }
  } catch (e) {
    return false
  }
  return false
}

export function isIE() {
  const userAgent = navigator.userAgent
  return userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1
}

// 是否为手机端状态， width <= 768
export function isMobileWidth() {
  return window.innerWidth <= 768
}

/**
 * @desc 判断参数是否为空, 包括null, undefined, [], '', {}
 * @param {object} obj 需判断的对象
 */
export function isEmpty(obj: any) {
  var empty = false

  if (obj === null || obj === undefined) { // null and undefined
    empty = true
  } else if ((isArray(obj) || isString(obj)) && obj.length === 0) {
    empty = true
  } else if (isObject(obj)) {
    var hasProp = false
    for (let prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        hasProp = true
        break
      }
    }
    if (!hasProp) {
      empty = true
    }
  } else if (isNumber(obj) && isNaN(obj)) {
    empty = true
  }
  return empty
}

/**
 * @desc 判断参数是否为空字符串, 比isEmpty()多判断字符串中全是空格的情况, 如: '   '.
 * @param {string} str 需判断的字符串
 */
export function isBlank(str: string) {
  if (isEmpty(str)) {
    return true
  } else if (isString(str) && str.trim().length === 0) {
    return true
  }
  return false
}

/**
 * @desc 生成时间戳
 */
export function createTimestamp() {
  return new Date().getTime()
}

/**
 * @desc 将字符转为16进制
 * @param {string} str 需要转换的字符串
 */
export function strToHex(str: string) {
  var val = ''
  for (var i = 0; i < str.length; i++) {
    val += str.charCodeAt(i).toString(16)
  }
  return val
}

/**
 * @desc 判断时间是否过期
 * @param {string} time 传入时间
 */
export function judgeTime(time: any) {
  var strtime = time.replace('/-/g', '/') // 时间转换
  // 时间
  var date1 = new Date(strtime)
  // 现在时间
  var date2 = new Date()
  // 判断时间是否过期
  return date1 < date2
}

/**
 * @desc 获取导航栏’？‘后面的参数
 */
export function urlParser() {
  let query: any = {}
  let url: any = []
  if (window.location.search.slice(1)) {
    url = window.location.search.slice(1).split('&')
  } else if (window.location.hash.slice(1).split('?')[1]) {
    url = window.location.hash.slice(1).split('?')[1].split('&')
  }
  url.forEach(function (item: any) {
    let items = item.split('=')
    query[items[0]] = items[1]
  })
  return query
}

/**
 * 时间戳转为正常时间格式
 * @ date 时间戳 整数
 * @ flg 需要转换的格式 默认'Y-M-D-H-M-S'，2种格式'Y-M-D' 'Y-M-D-H-M-S'
 */
export const formatDate = (date: any, flg: string = 'Y-M-D-H-M-S') => {
  let time = new Date(parseFloat(date) * 1000)
  let y = time.getFullYear()
  let m = time.getMonth() + 1
  let d = time.getDate()
  let h = time.getHours()
  let mm = time.getMinutes()
  let s = time.getSeconds()

  if (flg === 'Y-M-D') {
    return y + '-' + add0(m) + '-' + add0(d)
  } else {
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s)
  }
}

// 个位加0
const add0 = (m: number) => {
  return m < 10 ? '0' + m : m
}

//计算两时间差 精确到天
export const getDifferTime =(startDate, endDate)=> {
  let startTime = new Date(Date.parse(startDate.replace(/-/g, "/"))).getTime();
  let endTime = new Date(Date.parse(endDate.replace(/-/g, "/"))).getTime();
  let dates = Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24);
  return dates;
}

/**
 * byte
 * @ bytes
 */
export const byteConvert = function (bytes: any) {
  if (isNaN(bytes)) {
    return ''
  }
  const symbols = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  let exp = Math.floor(Math.log(bytes) / Math.log(2))
  if (exp < 1) {
    exp = 0
  }
  const i = Math.floor(exp / 10)
  bytes = bytes / Math.pow(2, 10 * i)
  if (bytes.toString().length > bytes.toFixed(2).toString().length) {
    bytes = bytes.toFixed(2)
  }
  // return bytes + symbols[i]
  let obj:any = {bytes, unit: symbols[i]}
  return obj
}

/**
 * 复制到剪切板
 * @ text：要复制的内容   callback： 回调
 */
export const copyText = (text: any, callback?: any) => { // text: 要复制的内容， callback: 回调
  let tag = document.createElement('textarea')
  tag.setAttribute('id', 'cp_hgz_input')
  tag.value = text
  document.getElementsByTagName('body')[0].appendChild(tag)
  // @ts-ignore
  document.getElementById('cp_hgz_input').select()

  console.log('tag=======value',tag.value)
  document.execCommand('copy')

  window.addEventListener('copy',(event)=>{
    console.log('event======>',event)
  })

  // console.log('粘贴板数据======>',window.clipboardData.getData())

  // @ts-ignore
  document.getElementById('cp_hgz_input').remove()
  if (callback) {
    callback(text)
  }
}

/**
 * 判断是否运行在微信端
 */
export const isWeiXin = () => {
  let ua = window.navigator.userAgent.toLowerCase()
  // @ts-ignore
  return ua.match(/MicroMessenger/i) == 'micromessenger'
}

export const getSysTem = () => {
  if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
    let ua = window.navigator.userAgent.toLowerCase()
    // @ts-ignore
    if(ua.match(/MicroMessenger/i) == "micromessenger") { 
      // console.log("在手机端微信上打开的"); 
      return 'wx'
    } else {
      return 'mobile';
      // console.log("在手机上非微信上打开的"); 
    } 
  } else {
    return 'pc'
    // console.log("在PC端上打开的");
  }
}

//深拷贝转浅拷贝
export const copyObject=(obj)=> {
  if(newArr ==null || newArr == undefined)return
  var newArr = obj.constructor === Array ? [] : {};
  if (typeof obj !== 'object') {
      return;
  }
  for (var i in obj) {
      newArr[i] = typeof obj[i] === 'object' ? copyObject(obj[i]) : obj[i];
  }
  return newArr
}
//树形菜单递归过滤
export const generateRoute=(menuList)=>{
  let routes = []
  const deepList =(list)=>{
    while(list.length){
        let item=list.pop()
        if( !item.children){
          routes.push({
            name:item.mneuCode,
            path:item.path,
            meta:{
                title:item.menuName
            },
            component:item.commentPath
          })
        }
        if(item.children && !item.action){
            deepList(item.children)
        }
    }
  } 
  deepList(menuList)
  return routes
}

//处理菜单过滤按钮
export const formatData = (data) => {
  data?.forEach(element => {
      if (element.menuType !== 2) {
          formatData(element.children)
          if (element.action) {
              delete element.children
          }
      } else {
          delete element.children
      }
  })
  return data
}
